package com.andy.basics;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;

public class BssPhaseListener implements PhaseListener {

	public int indent = 0;
	public static final int INDENTSIZE = 2;

	public void afterPhase(final PhaseEvent event) {

		// Lifecycle lc = (Lifecycle) event.getSource();

		HttpServletRequest req = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();

		System.out.println("Parameters: ");
		for (Object oB : req.getParameterMap().keySet()) {
			System.out.println("Parameter: " + oB + "->"
					+ req.getParameter(oB.toString()));
		}

		// printComponentTree(FacesContext.getCurrentInstance().getViewRoot(),
		// FacesContext.getCurrentInstance());

	}

	public void beforePhase(final PhaseEvent event) {
		System.out.println("Before " + event.getSource());
	}

	public PhaseId getPhaseId() {
		// return PhaseId.RESTORE_VIEW;
		// return PhaseId.ANY_PHASE;
		return PhaseId.RENDER_RESPONSE;
	}

	public void printComponentTree(final UIComponent comp,
			final FacesContext facesContext) {
		printComponentInfo(comp, facesContext);

		List complist = comp.getChildren();
		if (complist.size() > 0) {
			this.indent++;
		}
		for (int i = 0; i < complist.size(); i++) {
			UIComponent uicom = (UIComponent) complist.get(i);
			printComponentTree(uicom, facesContext);
			if (i + 1 == complist.size()) {
				this.indent--;
			}
		}

	}

	public void printComponentInfo(final UIComponent comp,
			final FacesContext facesContext) {

		if (comp.getId() == null) {
			System.out.println("UIViewRoot" + " " + "("
					+ comp.getClass().getName() + ")");
		} else {
			printIndent();
			System.out.println("|");
			printIndent();
			System.out.println(comp.getClientId(facesContext)
					+ " "
					+ "("
					+ comp.getClass().getName()
					+ "): Value: "
					+ (comp instanceof UIInput ? ((UIInput) comp)
							.getSubmittedValue() : "NA"));
		}

	}

	public void printIndent() {
		for (int i = 0; i < this.indent; i++) {
			for (int j = 0; j < BssPhaseListener.INDENTSIZE; j++) {
				System.out.print(" ");
			}
		}
	}

}
